package wang.chunfan.mybatis.log;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import wang.chunfan.mybatis.pojo.AbstractLog;
import wang.chunfan.mybatis.redis.RedisKeys;

import java.util.concurrent.*;

@Component
public class LogProducer {

    @Autowired
    private RedisTemplate redisTemplate;
    // 为线程池的线程设置有意义的名字
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("log-producer-pool-%d").build();
    // 创建线程池
    private ExecutorService pool = new ThreadPoolExecutor(5, 200, 0, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    private static String logKey = RedisKeys.getLogKey();

    public void saveLog(AbstractLog log) {
        pool.execute(() -> redisTemplate.opsForList().leftPush(logKey, log));
    }

}
